package com.jh.paymentchannel.util.jifuquick;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.service.JFQuickTopupRequest;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 获取支付令牌
 * 
 * @author tinn
 *
 */
public class PayGetToken {
	
	private static final Logger log = LoggerFactory.getLogger(PayGetToken.class);

	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	
	public String token(String Key, String tokenType, String ordercode, String partnerNo, String JFurl) throws IOException {
		
		String paytxnCode = "700001";
		String payapi = "/rest/api/"+paytxnCode;
		
		JSONObject dto = new JSONObject();
		dto.put("tokenType", tokenType);// 令牌类型
		dto.put("head", this.getHead(ordercode, partnerNo, paytxnCode));
		
		String execute = this.execute(Key, JFurl, payapi, dto.toString(), partnerNo, ordercode);
		
		log.info(execute);
		
		String res;
		//返回状态码
		String respCode;
		String respMsg;
		JSONObject jsonObject;
		
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0,16));
			
			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject======="+jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			String token = jsonObject.getString("token");
			log.info("head======="+head);
			log.info("token======="+token);
			respCode = head.getString("respCode");
			log.info("respCode====="+respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======"+respMsg);
			
			if("000000".equals(respCode) && "success".equalsIgnoreCase(respMsg)){
				return token.toString();
			}else {
				return "failed";
			}
			
		} catch (Exception e) {
			return "failed";
		}
		
	}
	
	
	
	
	
	public String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		System.out.println("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		System.out.println("encryptData : " + params.get("encryptData"));
		System.out.println("sign : " + params.get("sign"));
		System.out.println("partnerNo : " + params.get("partnerNo"));

		System.out.println("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			System.out.println("============ 返回报文原文:" + resStr);
			
			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	 
    
	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}
	
}
